package com.zhang.common.exception;

import com.zhang.common.lang.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;


//全局捕获异常
@Slf4j
@RestControllerAdvice   //表明从Controller层面捕获异常
public class GlobalExceptionHandler {

    //spring-boot-starter-validation工具包校验出数据不符合格式报此异常
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public Result handler(MethodArgumentNotValidException e){
        BindingResult result = e.getBindingResult();
        ObjectError error = result.getAllErrors().stream().findFirst().get();
        log.error("实体类校验异常：--------{}",error.getDefaultMessage());
        return Result.fail(error.getDefaultMessage());
    }


    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(value = RuntimeException.class)
    public Result handler(RuntimeException e){
        log.error("运行时异常：--------{}",e.getMessage());

        return Result.fail(e.getMessage().equals("不允许访问")?"你没有权限":e.getMessage());
    }

    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(value = IllegalAccessException.class)
    public Result handler(IllegalAccessException e){
        log.error("Assert异常：--------{}",e.getMessage());
        return Result.fail(e.getMessage());
    }
}
